package xyc.sjxy.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String methodName = req.getParameter("m"); // 假设请求参数包含方法名
        // 从请求的路径信息中获取方法名，去除开头的斜杠
        String methodName = req.getPathInfo().substring(1);
        // /api/13 /api/login /api/reg --》 /13 /login /reg   就是访问路径的参数
        // /api/a/b/123  --》/a/b/123
         System.out.println("methodName = " + methodName);
        try {
            // 反射获取方法并调用
            // 使用正确的参数类型：HttpServletRequest和HttpServletResponse
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println("method.getName() = " + method.getName());
            Object result = method.invoke(this, req, resp); // 调用方法，传递实际的req和resp对象
            //resp.getWriter().write(result != null ? result.toString() : "");
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("Failed to invoke method", e);
        }
    }
}
